package com.peg.rules;

import com.peg.dataobjects.Context;

/**
 * @author sad
 */
public abstract class ContainerRule extends Rule {

    private boolean _forceRestoreState;
    private String name;

    public void setName(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }

    protected void setForceRestoreState(boolean forceRestoreState) {
        _forceRestoreState = forceRestoreState;
    }

    @Override
    protected boolean executeRule(Rule rule, Context context) {
        int startMatchIndex = context.getCurrentStreamIndex();
        context.inLevel();
        boolean result = super.executeRule(rule, context);
        context.outLevel(!_forceRestoreState && result);

        if (_forceRestoreState) {
            context.setCurrentStreamIndex(startMatchIndex - 1);
        } else {
            if (result) {
                int endMatchIndex = context.getCurrentStreamIndex();
                context.setMatch(startMatchIndex, endMatchIndex - startMatchIndex);
            } else {
                context.setCurrentStreamIndex(startMatchIndex);
            }
        }

        if (rule instanceof Rule) {
            ((Rule) rule).endRule(result, context);
        }

        _forceRestoreState = false;
        return result;
    }

    @Override
    public String toString() {
        String _name = getName();
        if (_name != null && !_name.isEmpty()) {
            return getName();
        } else {
            return super.toString();
        }
    }
}
